package io.lkt.modules.sys.controller;

import com.google.common.collect.Lists;
import io.lkt.common.annotation.SysLog;
import io.lkt.common.redis.RedisCacheUtil;
import io.lkt.common.utils.PageUtils;
import io.lkt.common.utils.R;
import io.lkt.common.validator.Assert;
import io.lkt.common.validator.ValidatorUtils;
import io.lkt.common.validator.group.AddGroup;
import io.lkt.common.validator.group.UpdateGroup;
import io.lkt.modules.sys.entity.SysGzhEntity;
import io.lkt.modules.sys.entity.SysUserEntity;
import io.lkt.modules.sys.nopassword.NoPwdUtils;
import io.lkt.modules.sys.qrcode.QRCodeUtil;
import io.lkt.modules.sys.service.SysUserRoleService;
import io.lkt.modules.sys.service.SysUserService;
import io.lkt.modules.sys.shiro.ShiroUtils;

import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import jodd.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping({"/sys/user"})
public class SysUserController
		extends AbstractController
{
	@Autowired
	RedisCacheUtil redisCacheUtil;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Value("${title}")
	private String title;

	@RequestMapping({"/list"})
	@RequiresPermissions({"sys:user:list"})
	public R list(@RequestParam Map<String, Object> params)
	{
		PageUtils page = this.sysUserService.queryPage(params);

		List<?> list = page.getList();

		if (CollectionUtils.isNotEmpty(list)) {
			List<SysUserEntity> sysUserList = Lists.newArrayList();

			for (Object temp : list) {
				SysUserEntity sysUserEntity = (SysUserEntity) temp;

				String openId = Optional.ofNullable(sysUserEntity.getOpenId()).orElse("");

				sysUserEntity.setOpenStatus(0);
				if(StringUtil.isNotBlank(openId)){
					sysUserEntity.setOpenStatus(1);
				}

				sysUserList.add(sysUserEntity);
			}
			page.setList(sysUserList);
		}
		return R.ok().put("page", page);
	}

	@RequestMapping({"/info"})
	public R info()
	{
		SysUserEntity user = getUser();
		if(StringUtil.isNotBlank(user.getOpenId())){
			user.setOpenStatus(1);
		}
		return R.ok().put("user", user);
	}

	@RequestMapping({"/getTitle"})
	public R getTitle()
	{
		return R.ok().put("title", this.title);
	}

	@SysLog("修改密码")
	@RequestMapping({"/password"})
	public R password(String password, String newPassword)
	{
		Assert.isBlank(newPassword, "新密码不为能空");

		password = ShiroUtils.sha256(password, getUser().getSalt());

		newPassword = ShiroUtils.sha256(newPassword, getUser().getSalt());

		boolean flag = this.sysUserService.updatePassword(getUserId(), password, newPassword);
		if (!flag) {
			return R.error("原密码不正确");
		}
		return R.ok();
	}

	@RequestMapping({"/info/{userId}"})
	@RequiresPermissions({"sys:user:info"})
	public R info(@PathVariable("userId") Long userId)
	{
		SysUserEntity user = (SysUserEntity)this.sysUserService.getById(userId);

		if(StringUtil.isNotBlank(user.getOpenId())){
			user.setOpenStatus(1);
		}

		List<Long> roleIdList = this.sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);

		List<String> gzhCodeList = this.sysUserRoleService.queryGzhCodeList(userId);
		user.setGzhCodeList(gzhCodeList);

		return R.ok().put("user", user);
	}

	@SysLog("保存用户")
	@RequestMapping({"/save"})
	@RequiresPermissions({"sys:user:save"})
	public R save(@RequestBody SysUserEntity user)
	{
		ValidatorUtils.validateEntity(user, new Class[] { AddGroup.class });

		this.sysUserService.saveUser(user);

		return R.ok();
	}

	@SysLog("修改用户")
	@RequestMapping({"/update"})
	@RequiresPermissions({"sys:user:update"})
	public R update(@RequestBody SysUserEntity user)
	{
		ValidatorUtils.validateEntity(user, new Class[] { UpdateGroup.class });

		this.sysUserService.update(user);

		return R.ok();
	}

	@SysLog("删除用户")
	@RequestMapping({"/delete"})
	@RequiresPermissions({"sys:user:delete"})
	public R delete(@RequestBody Long[] userIds)
	{
		if (ArrayUtils.contains(userIds, Long.valueOf(1L))) {
			return R.error("系统管理员不能删除");
		}
		if (ArrayUtils.contains(userIds, getUserId())) {
			return R.error("当前用户不能删除");
		}
		this.sysUserService.removeByIds(Arrays.asList(userIds));

		return R.ok();
	}

	@RequestMapping({"/selectGzhList"})
	public R selectGzhList()
	{
		List<SysGzhEntity> list = this.sysUserRoleService.selectGzhList();

		return R.ok().put("list", list);
	}

	@SysLog("解绑微信")
	@RequestMapping({"/cutWeChat"})
	public R password(@RequestBody Long userId){

		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setUserId(userId);
		userEntity.setOpenId("");

		boolean flag = this.sysUserService.updateById(userEntity);
		if (!flag) {
			return R.error("解绑失败");
		}
		return R.ok();
	}

	@RequestMapping("/hasPermission")
	public R hasPermission(@RequestParam String permission) {
		boolean result = SecurityUtils.getSubject().isPermitted(permission);
		return R.ok().put("isPermitted", result);
	}
}
